package com.zlp.config;

import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.zlp.dto.CacheUpload;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;

@Slf4j
public class PutObjectProgressListener implements ProgressListener {


    private String uploadNo;
    private long bytesWritten = 0;
    private long totalBytes = -1;
    private boolean succeed = false;
    private BigDecimal percent = new BigDecimal(0.00);
    Long sum = 0L;


    public PutObjectProgressListener(String uploadNo, Long sum) {
        this.uploadNo = uploadNo;
        this.sum = sum;
    }

    @Override
    public void progressChanged(ProgressEvent progressEvent) {

        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                // logger.info("Start to upload......");
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                // logger.info(this.totalBytes +
                // " bytes in total will be uploaded to OSS");
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    double progress = this.bytesWritten * 100.0 / this.totalBytes;
                    percent = new BigDecimal(progress).setScale(2, BigDecimal.ROUND_HALF_UP);
                    // 将进度percent放入session中
                    CacheUpload.putProgressBar(uploadNo,percent);
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;

                break;
            case TRANSFER_FAILED_EVENT:

                break;
            default:
                break;
        }

        //图片进度打印控制台 
       log.info("percent:" + percent);
    }

    public boolean isSucceed() {
        return succeed;
    }


}

